from flask import request, jsonify,render_template,g,redirect,current_app,session

from info import constants,db
from info.utils.commony import user_login_data
from info.utils.qiniu_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route("/info")
@user_login_data
def info():
    user = g.user
    data = {"user_info": user.to_dict() if user else None,}
    return render_template("news/user.html",data = data)


@profile_blu.route("/base_info", methods=["GET",'POST'])
@user_login_data
def base_info():
    """基本资料"""
    user = g.user
    if not user:
        # 用户未登录，重定向到主页
        return redirect('/')

    if request.method == 'GET':
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_base_info.html", data=data)

    # json数据获取
    data_dict = request.json
    signature = data_dict.get("signature")
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")

    # 数据判断
    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    if gender not in ('WOMAN','MAN'):
        return jsonify(errno=RET.PARAMERR, errmsg="性别选择错误")


    # 数据提交
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 刷新session的nick_name
    session["nick_name"] = nick_name

    # 4. 返回操作结果
    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route("/pic_info", methods=["GET",'POST'])
@user_login_data
def pic_info():
    """头像设置"""
    user = g.user
    if not user:
        # 用户未登录，重定向到主页
        return redirect('/')

    if request.method == 'GET':
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_pic_info.html", data=data)

    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="文件类型错误")

    # 获取图片地址
    try:
        avatar_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传错误")

    # 图片地址添加
    user.avatar_url = avatar_url
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    data = {
        'avatar_url':constants.QINIU_DOMIN_PREFIX + avatar_url
    }

    return jsonify(errno=RET.OK,errmsg="上传成功",data=data)


@profile_blu.route("/pass_info", methods=["GET",'POST'])
@user_login_data
def pass_info():
    """密码修改"""
    user = g.user
    if not user:
        # 用户未登录，重定向到主页
        return redirect('/')

    if request.method == 'GET':
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_pass_info.html", data=data)

    # 获取参数
    data_dict = request.json
    old_password = data_dict.get('old_password')
    new_password = data_dict.get('new_password')
    new_password2 = data_dict.get('new_password2')

    # 参数判断
    if not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="不许为空")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg="密码错误")
    if new_password != new_password:
        return jsonify(errno=RET.PARAMERR, errmsg="密码不一致")
    if old_password == new_password:
        return jsonify(errno=RET.PARAMERR, errmsg="密码未修改")

    # 密码提交
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 返回操作结果
    return jsonify(errno=RET.OK, errmsg="保存成功")